package tech.xs.common.framework.util;


import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import tech.xs.common.auth.domain.cache.AuthTokenCache;
import tech.xs.common.auth.domain.enums.AuthClientTypeEnum;
import tech.xs.common.auth.util.AuthTokenUtil;
import tech.xs.common.framework.holder.SpringContextHolder;
import tech.xs.common.sys.domain.bo.CurrLoginUserBo;

public class AuthUtil {


    public static CurrLoginUserBo getCurrLoginUser() {
        AuthHeaderUtil.AuthHeader headToken = AuthHeaderUtil.getAuthHeader();
        if (headToken == null) {
            return null;
        }
        RedissonClient redissonClient = SpringContextHolder.getBean(RedissonClient.class);
        RBucket<AuthTokenCache> authTokenBucket = redissonClient.getBucket(AuthTokenUtil.getTokenCacheKey(headToken.getUserId(), headToken.getClientType()));
        AuthTokenCache authTokenCache = authTokenBucket.get();
        if (authTokenCache == null) {
            return null;
        }
        CurrLoginUserBo currUser = new CurrLoginUserBo();
        currUser.setUserId(authTokenCache.getUserId());
        currUser.setUserName(authTokenCache.getUserName());
        currUser.setClientType(authTokenCache.getClientType());
        currUser.setRoleCodes(authTokenCache.getRoleCodes());
        currUser.setPermissionCodes(authTokenCache.getPermissionCodes());
        return currUser;
    }

    /**
     * 获取当前登陆用户ID
     *
     * @return 用户id
     */
    public static Long getCurrUserId() {
        AuthHeaderUtil.AuthHeader headToken = AuthHeaderUtil.getAuthHeader();
        if (headToken == null) {
            return null;
        }
        return headToken.getUserId();
    }

    /**
     * 获取当前登陆客户端类型
     *
     * @return 客户端类型
     */
    public static AuthClientTypeEnum getCurrClientType() {
        AuthHeaderUtil.AuthHeader headToken = AuthHeaderUtil.getAuthHeader();
        if (headToken == null) {
            return null;
        }
        return headToken.getClientType();
    }


}
